<?php

class Config {
	private static $configs = array();

	public static function get($path) {
		$_ = new self;
		$f = $_->match($path);
		if (is_null($f)) {
			throw new Exception("No config available for {$path}");
		} else {
			return $f;
		}
	}

	public static function search($path) {
		$_ = new self;
		return $_->match($path);
	}

	private static $cache = array();
	protected function match($path) {
		if (!isset(self::$cache[$path])) {
			$nodes = explode('.', $path);
			$root = array_shift($nodes);
			self::$cache[$path] = $this->find($nodes, $this->load($root));
		}
		return self::$cache[$path];
	}

	private function find($nodes, $config){
		while ($nodes) {
			$node = array_shift($nodes);
			if (!isset($config[$node])) {
				$config = null;
				break;
			}
			$config = $config[$node];
		}
		return $config;

	}

	private function load($root) {
		if(!isset(self::$configs[$root])) {
			$config = array();
			if (file_exists(ROOT . "/config/{$root}.php")) {
				$config = include(ROOT . "/config/{$root}.php");

      /*
			} elseif (($data = DynamicConfig::load($root))) {
				foreach (explode("\n", $data->value) as $config_data) {
					if (!preg_match("/([^:]+):(.*)/", $config_data, $matches)) continue;
					list($_, $key, $value) = $matches;
					$_data = trim($value);
					foreach (array_reverse(explode('.', trim($key))) as $k) {
						$_data_ = array($k => $_data);
						$_data = $_data_;
					}
					$config = array_merge_recursive($config, $_data);
				}
      */
			}
			self::$configs[$root] = $config;
		}
		return self::$configs[$root];
	}
}
/*
class DynamicConfig extends Node {
	public static function option() {
		return array(
			'table' => 'ave_dynamic_config',
			'key' => 'key',
			'columns' => array(
				'key' => 'key',
				'value' => 'value',
				'created' => 'created',
				'updated' => 'updated',
				'attributeData' => 'attributes',
			));
	}
}*/